using UnityEngine;
using QFramework;

namespace ProjectMyFarmAndShe
{
	public partial class CameraController : ViewController
	{
		public static CameraController Default;

		private void Awake()
		{
			Default = this;
		}
		
		private float shakeDuration = 0f;
		private float shakeMagnitude = 0.1f;
		private float dampingSpeed = 1.0f;
		private bool ShakeStart = false;
		
		private void Start()
		{
		}
		
		public void Shake(float duration, float magnitude)
		{
			shakeDuration = duration;
			shakeMagnitude = magnitude;
			ShakeStart = true;
		}
		
		private void Update()
		{
			if (ShakeStart)
			{
				var currentPos = transform.position;
				
				if (shakeDuration > 0)
				{
					transform.localPosition = currentPos + Random.insideUnitSphere * shakeMagnitude;
					shakeDuration -= Time.deltaTime * dampingSpeed;
				}
				else
				{
					shakeDuration = 0f;
					transform.position = currentPos;
					ShakeStart = false;
				}
			}
			else
			{
				if (Global.Player)
				{
					//目标位置
					var targetPosition =
						new Vector2(Global.Player.transform.position.x, Global.Player.transform.position.y);
					//当前摄像机位置
					Vector3 currentPosition = transform.position;
					//计算当前应该到达位置（平滑算法）
					currentPosition = Vector2.Lerp(transform.position, targetPosition,
						(1.0f - Mathf.Exp(-Time.deltaTime * 5)));
					currentPosition.z = -10;
					//设置位置
					transform.position = currentPosition;
				}
			}
			
		}

		private void OnDestroy()
		{
			Default = null;
		}
	}
}
